package com.industrial.white.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ArrayUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.enums.WriteDirectionEnum;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.industrial.common.core.domain.R;
import com.industrial.common.core.web.controller.BaseController;
import com.industrial.common.core.web.domain.AjaxResult;
import com.industrial.common.core.web.page.TableDataInfo;
import com.industrial.common.security.annotation.Logical;
import com.industrial.common.security.annotation.RequiresRoles;

import com.industrial.system.api.domain.AdminUser;
import com.industrial.system.api.domain.EmEnterpriseInformationCollection;
import com.industrial.white.domain.dto.EnterExportDto;
import com.industrial.white.domain.vo.ChooseField;
import com.industrial.white.handler.excel.ExcelFillCellLineMergeHandler;
import com.industrial.white.handler.excel.ExcelMergeChooseFieldHandler;
import com.industrial.white.handler.excel.TableTitleHandler;
import com.industrial.white.service.IEmEnterpriseInformationCollectionService;
import com.industrial.white.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 企业基本信息Controller
 *
 * @author ruoyi
 * @date 2023-08-15
 */
@RestController
@RequestMapping("/enterinfo/collection")
public class EmEnterpriseInformationCollectionController extends BaseController {


    private IEmEnterpriseInformationCollectionService emEnterpriseInformationCollectionService;

    @Value("${template.excel}")
    private String templePath;

    @Autowired
    public EmEnterpriseInformationCollectionController(IEmEnterpriseInformationCollectionService emEnterpriseInformationCollectionService) {
        this.emEnterpriseInformationCollectionService = emEnterpriseInformationCollectionService;
    }

    /**
     * 保存亩产中的企业信息到白名单中
     * @return
     */
    @PostMapping("/savePreMuCompanyInfoToWhite")
    public R<Boolean> savePreMuCompanyInfoToWhite(@RequestBody Map<String,Object> params){
        emEnterpriseInformationCollectionService.savePreMuCompanyInfoToWhite(params);
        return R.ok(true);
    }

    /**
     * 判断亩产的企业是否存在白名单中
     * @return
     */
    @GetMapping("/preMuExistWhite/{uscc}")
    public R<Boolean> preMuExistWhite(@PathVariable("uscc") String uscc){
        Boolean isExist = emEnterpriseInformationCollectionService.preMuExistWhite(uscc);
        return R.ok(isExist);
    }

    /**
     * 查询传入USCC是否存在白名单中
     * @return
     */
    @PostMapping("/preMuExistWhiteByUscc")
    public R<List<String>> preMuExistWhiteByUscc(@RequestBody List<String> uscc){
        List<String> strings = emEnterpriseInformationCollectionService.preMuExistWhiteByUscc(uscc);
        return R.ok(strings);
    }


    /**
     * 获取企业信息
     * @return
     */
    @GetMapping("/getEnterDataInfo")
    public AjaxResult getEnterDataInfo(){
        EmEnterpriseInformationCollection e = this.emEnterpriseInformationCollectionService.getEnterDataInfo();
        return AjaxResult.success(e);
    }

    /**
     * 查询企业基本信息列表
     */
    @GetMapping("/list")
    public TableDataInfo list(EmEnterpriseInformationCollection emEnterpriseInformationCollection)
    {
        startPage();
        List<EmEnterpriseInformationCollection> list = emEnterpriseInformationCollectionService.selectEmEnterpriseInformationCollectionList(emEnterpriseInformationCollection);
        return getDataTable(list);
    }

    /**
     * 通过Id查询企业信息
     * @param baseId
     * @return
     */
    @GetMapping(value = "/{baseId}")
    public AjaxResult getInfo(@PathVariable("baseId") String baseId)
    {
        return success(emEnterpriseInformationCollectionService.selectEmEnterpriseInformationCollectionByBaseId(baseId));
    }


    /**
     * 修改企业基本信息
     */
    @PutMapping
    public AjaxResult edit(@RequestBody EmEnterpriseInformationCollection emEnterpriseInformationCollection)
    {
        return toAjax(emEnterpriseInformationCollectionService.updateEmEnterpriseInformationCollection(emEnterpriseInformationCollection));
    }

    @PostMapping
    public AjaxResult add(@RequestBody EmEnterpriseInformationCollection emEnterpriseInformationCollection)
    {
        return toAjax(emEnterpriseInformationCollectionService.insertEmEnterpriseInformationCollection(emEnterpriseInformationCollection));
    }

    /**
     * 导出表格
     * @param response
     * @param enterParams
     */
    @RequiresRoles(value = {"x_01_011","s_01_011","p_01_011"},logical= Logical.OR)
    @PostMapping("/exportEnterDataMergeCell")
    public void exportEnterDataMergeCell(HttpServletResponse response, EmEnterpriseInformationCollection enterParams){

        /**
         * 当前登录的用户信息
         */
        AdminUser sysUser = this.emEnterpriseInformationCollectionService.selectCurrentLoginUserInfo();

        List<EnterExportDto> enterData = emEnterpriseInformationCollectionService.selectExportEnterData(enterParams);

        try(ServletOutputStream outputStream = response.getOutputStream();
            ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(templePath).registerWriteHandler(new ExcelFillCellLineMergeHandler(4)).build()){
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).direction(WriteDirectionEnum.VERTICAL).build();
            excelWriter.fill(new FillWrapper("data1", enterData), fillConfig, writeSheet);
            Map<String, Object> map = BeanUtil.beanToMap(sysUser);
            excelWriter.fill(map, writeSheet);
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("导出数据的过程中发生的未知异常");
        }
        System.out.println("导出成功");
    }

    /**
     * 选择字段导出企业的信息数据
     * @param response
     * @param params 前端传过来的参数。因为有多个实体类要接收。
     */
    @RequiresRoles(value = {"x_01_011","s_01_011","p_01_011"} ,logical= Logical.OR)
    @PostMapping("/selectFieldExport")
    public void selectFieldExport(HttpServletResponse response, @RequestParam Map<String,Object> params){
        /**
         * 当前登录的用户信息
         */
        AdminUser sysUser = this.emEnterpriseInformationCollectionService.selectCurrentLoginUserInfo();

        /**
         * 这个变量用来标识前端传来的数据
         * 有没有包含统一社会信用代码列
         *
         * 在进行单元格合并操作的时候，合并的
         * 标识是通过统一社会信用代码合并的。
         * 所以如果前端选择的导出字段不包含
         * 统一社会信用代码的时候，数据填充完成
         * 后需要将统一社会信用代码列删除
         */
        boolean isExist = true;
        List<String> arg = new ArrayList<>();
        for(Map.Entry<String,Object> entry : params.entrySet()){
            String key = entry.getKey();
            if(key.startsWith("fieldArgs")){
                arg.add(String.valueOf(entry.getValue()));
            }
        }
        if(!ArrayUtil.contains(arg.toArray(),"enter_usci")){
            isExist = false;
            arg.add("enter_usci");
        }
        //构建选择的字段
        ChooseField chooseField = new ChooseField();
        chooseField.setFieldArgs(arg);

        params.remove("fieldArgs");
        EmEnterpriseInformationCollection enter = BeanUtil.mapToBean(params, EmEnterpriseInformationCollection.class,false,null);
        List<EnterExportDto> enterExportDos = this.emEnterpriseInformationCollectionService.selectChooseFiedldData(chooseField, enter);

        Set<String> tf = new HashSet<>();
        for(String i : arg){
            String s = CommonUtil.underlineToCamel(i);
            tf.add(s);
        }
        tf.add("xh");
        if(ArrayUtil.contains(tf.toArray(),"isOriginalWhitelist")){
            tf.remove("isOriginalWhitelist");
            tf.add("originalWhitelist");
        }

        if(ArrayUtil.contains(tf.toArray(),"remark")){
            tf.remove("remark");
            tf.add("enterRemark");
        }
        try(ServletOutputStream outputStream = response.getOutputStream();){
            ExcelWriterSheetBuilder sheet = EasyExcel.write(outputStream,EnterExportDto.class)
                    .registerWriteHandler(new TableTitleHandler(tf.size(),sysUser))
                    .registerWriteHandler(new ExcelMergeChooseFieldHandler(3,tf))
                    .includeColumnFieldNames(tf).sheet("企业信息采集表");
            sheet.relativeHeadRowIndex(2).doWrite(enterExportDos);


        }catch (Exception e){
            e.printStackTrace();
        }

        System.out.println("导出成功");
    }


    /**
     * 修改审核状态
     * @param params
     * @return
     */
    @PostMapping("/checkEnter")
    public AjaxResult checkEnter(@RequestBody Map<String,String> params){
        this.emEnterpriseInformationCollectionService.checkEnter(params);
        return AjaxResult.success();
    }

    @PutMapping("/editEnter")
    public AjaxResult editEnter(@RequestBody EmEnterpriseInformationCollection emEnterpriseInformationCollection){
        return emEnterpriseInformationCollectionService.editEnter(emEnterpriseInformationCollection);
    }

    /**
     * <p>
     *     通过企业信息代码查询企业信息
     * </p>
     * @param uscc
     * @return
     */
    @GetMapping("/queryWhiteInfoByUscc/{uscc}")
    public R<EmEnterpriseInformationCollection> queryWhiteInfoByUscc(@PathVariable("uscc") String uscc){
        EmEnterpriseInformationCollection r = emEnterpriseInformationCollectionService.queryWhiteInfoByUscc(uscc);
        return R.ok(r);
    }


}
